using FJson;
using Framework.Save.Interface;
using Framework.Utils;
using UnityEngine;

namespace Framework.Save
{
    public class SaveSerializerJsonEncrypt : ISaveSerializer
    {
        private static byte[] _encryptMaps = {0x16 , 0x12 , 0x15 , 0xf1 , 0xd5 , 0x01 , 0x18 , 0x00, 0xf2 , 0x10 , 0xf6 , 0xf7 , 0xf9};
        public byte[] Serialize(object obj)
        {
            var json = FJsonUtility.ToJson(obj);
            var tBytes = FileHelper.StringToArrayByteUtf8(json);
            this.reverseBytes(0 , tBytes);
            return tBytes;
        }

        public T Deserialize<T>(byte[] value)
        {
            if (value == null)
                return default;
            this.reverseBytes(0 ,  value);
            var json = FileHelper.ArrayByteUtf8ToString(value);
            return FJsonUtility.ToObject<T>(json); 
        }
        
        
        public void reverseBytes(int index,  byte[] arr) {
            int j = arr.Length - 1;
            int el = _encryptMaps.Length;
            byte temp;
            while (index<j) {
                //替换
                temp   = arr[index];
                arr[index] = (byte)(arr[j] ^ _encryptMaps[index % el]);
                arr[j] = (byte)(temp ^ _encryptMaps[index % el]);
                index++;
                j--;
            }
        }
    }
}